package com.wswy.wzcx.widget.bubbleview;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.RectF;
import com.blankj.utilcode.util.SizeUtils;
import com.facebook.cache.common.CacheKey;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.common.references.CloseableReference;
import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.wswy.wzcx.widget.bubbleview.BubbleDrawable.ArrowLocation;

public class BubblePostprocessor extends BasePostprocessor {

  private static final String TAG = "BubblePostprocessor";

  private String key;
  private ArrowLocation arrowLocation;

  public BubblePostprocessor(String key, ArrowLocation arrowLocation) {
    this.key = key;
    this.arrowLocation = arrowLocation;
  }

  @Override
  public CloseableReference<Bitmap> process(
      Bitmap sourceBitmap,
      PlatformBitmapFactory bitmapFactory) {

    int maxW = SizeUtils.dp2px(200);
    int maxH = SizeUtils.dp2px(300);

    int sourceW = sourceBitmap.getWidth();
    int sourceH = sourceBitmap.getHeight();
    int w, h;

    if (sourceW > sourceH) {
      w = Math.min(sourceW, maxW);
      h = (int) Math.min(sourceH,
          ((float) w / sourceW) * sourceH);

    } else {

      h = Math.min(sourceH, maxH);

      w = (int) Math.min(sourceW,
          ((float) h / sourceH) * sourceW);
    }

    final CloseableReference<Bitmap> bitmapRef = bitmapFactory.createBitmap(w, h);

    try {
      final Bitmap destBitmap = bitmapRef.get();

      RectF rectF = new RectF(0, 0, w, h);

      BubbleDrawable bubbleDrawable = new BubbleDrawable.Builder()
          .rect(rectF)
          .arrowLocation(arrowLocation)
          .angle(SizeUtils.dp2px(6))
          .arrowHeight(SizeUtils.dp2px(8))
          .arrowWidth(SizeUtils.dp2px(10))
          .bubbleType(BubbleDrawable.BubbleType.BITMAP)
          .bubbleBitmap(sourceBitmap)
          .build();

      Canvas canvas = new Canvas(destBitmap);

      bubbleDrawable
          .setBounds(0, 0, bubbleDrawable.getIntrinsicWidth(), bubbleDrawable.getIntrinsicHeight());
      bubbleDrawable.draw(canvas);

      return CloseableReference.cloneOrNull(bitmapRef);
    } finally {
      CloseableReference.closeSafely(bitmapRef);
    }

  }

  @Override
  public CacheKey getPostprocessorCacheKey() {
    return new SimpleCacheKey(
        "----BubblePostprocessor---" + arrowLocation.name() + "-" + key);
  }
}
